package core

import (
	"log"
	"net/http/httptest"

	"gin-gateway/core/init"
	"gin-gateway/core/dao"
	"github.com/afex/hystrix-go/hystrix"
	"github.com/gin-gonic/gin"
)

func InitCircuitConfig() {
	circuit := dao.CircuitConfig{}

	tx, err := Init.GetGormPool("default_db")
	if err != nil {
		log.Fatalf("InitCircuitConfig err: %v", err)
	}
	c, _ := gin.CreateTestContext(httptest.NewRecorder())

	CircuitConfigList, err := circuit.FindAll(c, tx)
	if err != nil {
		log.Fatalf("InitCircuitConfig err: %v", err)
	}

	for i := range CircuitConfigList {
		hystrix.ConfigureCommand(CircuitConfigList[i].ServiceName, hystrix.CommandConfig{
			Timeout:                CircuitConfigList[i].Timeout * 1000,
			MaxConcurrentRequests:  CircuitConfigList[i].MaxConcurrentRequests,
			RequestVolumeThreshold: CircuitConfigList[i].RequestVolumeThreshold,
			SleepWindow:            CircuitConfigList[i].SleepWindow * 1000,
			ErrorPercentThreshold:  CircuitConfigList[i].ErrorPercentThreshold,
		})
	}
}

func UpdateCircuitConfig(serviceName string, circuitConfig *dao.CircuitConfig) {
	hystrix.ConfigureCommand(serviceName, hystrix.CommandConfig{
		Timeout:                circuitConfig.Timeout,
		MaxConcurrentRequests:  circuitConfig.MaxConcurrentRequests,
		RequestVolumeThreshold: circuitConfig.RequestVolumeThreshold,
		SleepWindow:            circuitConfig.SleepWindow,
		ErrorPercentThreshold:  circuitConfig.ErrorPercentThreshold,
	})
}
